package com.zhouheng.springbootmultithreading.common.utils;

import com.zhouheng.springbootmultithreading.common.exception.BaseException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpRequestUtils {

	private HttpRequestUtils(){

	}

    /**
     * http请求
     *
     * @param url   描述此参数
     * @return 返回 t 描述此返回参数
     * @author 周恒
     * @date 20180613 14:12:57
     * @since v1.0
     */
	public static String httpGetString(String url) throws IOException{
		HttpGet request = new HttpGet(url);
		try(CloseableHttpClient client = HttpClients.createDefault();
            CloseableHttpResponse response = client.execute(request)) {
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
			}
		}
		throw new BaseException("请求失败url:"+url);
	}

	/**
	 * 获取请求字节数组，请求图片用
	 *
	 * @param url 描述此参数
	 * @return 返回 byte [ ] 描述此返回参数
	 * @author 周恒
	 * @date 20181109 10:37:24
	 * @since v1.0
	 */
	public static byte[] httpGetImageBytes(String url) throws IOException {
		HttpGet  request = new HttpGet(url);
		try(CloseableHttpClient client = HttpClients.createDefault();
			CloseableHttpResponse response = client.execute(request)) {
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				return EntityUtils.toByteArray(response.getEntity());
			}
		}
		throw new BaseException("请求失败url:"+url);
	}

    public static String httpPostString(String url, String param) throws IOException {
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        StringEntity s = new StringEntity(param);
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");
        post.setEntity(s);
        HttpResponse res = client.execute(post);
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        }
        throw new BaseException("请求错误url:" + url + " param:" + param);
    }

}
